require 'net/http'
require 'uri'
require 'json'
require './const.rb'
# POST request
def request_fun(params, way, url, token, file = nil)
  url = URI.parse(url)
  payload = params
  media_types = ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']
  # 确认媒体请求的方式
  case way
  when 'POST', 'GET'
    count = 0
  when 'FORMDATA'
    count = 1
    payload = URI.encode_www_form(params)
  when 'UPLOAD'
    count = 2
  else
    return { error: 'Invalid request method.' }
  end
  media_type = media_types[count]
  # 构建HTTP请求
  if way == 'POST' then request = Net::HTTP::POST.new(url.path, { 'Content-Type' => media_type, 'Authorization' => token })
  else request = Net::HTTP::Get.new(url.request_uri, { 'Content-Type' => media_type , 'Authorization' => token })
  end
  # 转换请求体的格式
  # GET、POST 都是 JSON格式
  # UPLOAD 是 FORM DATA 格式
  case count
  when 0, 1
    request.body = payload.to_json
  when 2
    if file
      request.set_form([['file', file]], 'multipart/form-data')
    else
      return { error: 'File parameter is missing for UPLOAD method.' }
    end
  end
  # 发送请求
  # http = Net::HTTP.new(url.host, url.port)
  # http.use_ssl = (url.scheme == 'https')
  # response = http.request(request)
  response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') do |http|
    http.request(request)
  end
  result = {
    code: response.code,
    body: response.body
  }
  if way == 'UPLOAD'|| way == 'GET' then return response.body end
  JSON.parse(response.body)['data']
end

# get request


def requestGet(url, token)
  url = URI.parse(url)

  # 构建 HTTP 请求
  request = Net::HTTP::Get.new(url.request_uri, { 'Content-Type' => 'application/json', 'Authorization' => token })

  # 发送请求
  response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') do |http|
    http.request(request)
  end

  # 处理响应
#   result = {
#     code: response.code,
#     body: response.body
#   }
  # puts response.body
  # return JSON.parse(response.body)
  return response.body
end




# request({ "regex" => "W1935", "status" => 5, "business_type" => false },'POST','https://api.pooul.com/cms/merchants/regex_search',"5034c811636d256cc44184b0f3e9df585054e2be")
# request({
#     "account_num" => "6217002020035919893",
#     "account_type" => 0,
#     "bank_category_code" => "105",
#     "bank_full_name" => "",
#     "bank_name" => "中国建设银行",
#     "contact_mobile" => "13647006551",
#     "owner_name" => "张志伟",
#     "snb_bank_code" => "0",
# },"POST","https://api.pooul.com/web/public/bank_cards?merchant_id=9780009445460173","5034c811636d256cc44184b0f3e9df585054e2be")

def testup
  url = URI.parse('http://127.0.0.1:2222/upload') # 请求的 URL

  file_path = 'C://Users/coffe/Pictures/MIUI02.jpg' # 文件路径
  file = File.open(file_path)

  req = Net::HTTP::Post.new(url.path)
  req.set_form({'file' => file}, 'multipart/form-data')

  response = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end

  puts response.body
end